<script lang="ts" setup>
import { useGlobalDialog } from '@/hooks'
import { initPageDTO, initPageVO, type PageDTO, type PageVO, type ResultType } from '@/type/type'
import {
  addResourcesApi,
  delResourcesApi,
  getResourcesAdminPageApi,
  initResourcesDTO,
  type ResourcesDTO,
  type ResourcesVO,
  resourcesVO2DTO,
  updateResourcesApi
} from '@/request/api/resources'
import { useSystemStore } from '@/stores/system'
import { ClassifyEnum, DialogEnum } from '@/enum'
import { addToFormData } from '@/utils'
import { useTemporaryStore } from '@/stores/temporary'

const systemStore = useSystemStore()
const temporaryStore = useTemporaryStore()

const { globalDialog } = useGlobalDialog()

const form = ref<ResourcesDTO>(initResourcesDTO())
const formRef = ref<any>()
const pageVO = ref<PageVO<ResourcesVO>>(initPageVO())
const ids = ref<number[]>([])
const isAdd = ref<boolean>(true)
/** 查询列表 */
let page = reactive<PageDTO>(initPageDTO())

const rules = {
  name: [{ required: true, message: '文件名不能为空', trigger: 'blur' }],
  labelId: [{ required: true, message: '标签不能为空', trigger: 'blur' }],
  remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
}

const getList = () => {
  getResourcesAdminPageApi(page).then((res: ResultType<PageVO<ResourcesVO>>) => {
    pageVO.value = res.data
  })
}

// 多选框选中数据
const handleSelectionChange = (selection: ResourcesVO[]) => {
  ids.value = selection.map((item) => item.id)
}

/** 新增按钮操作 */
const handleAdd = () => {
  form.value = initResourcesDTO()
  isAdd.value = true
  checkList.value = []
  systemStore.dialog.resources = true
}

/** 修改按钮操作 */
const handleUpdate = (row: ResourcesVO) => {
  form.value = resourcesVO2DTO(row)
  isAdd.value = false
  if (form.value.remark) {
    checkList.value = form.value.remark.split(',')
  }
  systemStore.dialog.resources = true
  temporaryStore.form.classifyId = row.label.classifyId
  temporaryStore.form.labelId = row.label.id
}

/** 删除按钮操作 */
const handleDelete = async (idArr: Array<number>) => {
  await globalDialog('确定删除 ID 为"' + idArr + '"的资源?').then((res: boolean) => {
    if (res) {
      delResourcesApi(idArr).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

/** 启用停用按钮操作 */
const handleChangeStatus = async (id: number, status: boolean) => {
  const resources: ResourcesDTO = initResourcesDTO()
  resources.id = id
  resources.status = status
  const title = status ? '启用' : '停用'
  await globalDialog('确定' + title + ' ID 为"' + id + '"的资源?').then((res: boolean) => {
    if (res) {
      updateResourcesApi(resources).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

/** 提交按钮 */
const submitForm = () => {
  // 添加标签ID
  form.value.labelId = temporaryStore.form.labelId
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id != undefined) {
        await globalDialog('确定修改 ID 为"' + form.value.id + '"的资源?').then((res: boolean) => {
          if (res) {
            updateResourcesApi(form.value).then(() => {
              systemStore.dialog.resources = false
              getList()
            })
          }
        })
      } else {
        temporaryStore.upload.formData = addToFormData(temporaryStore.upload.formData, form.value)
        addResourcesApi(temporaryStore.upload.formData).then(() => {
          temporaryStore.upload.init()
          systemStore.dialog.resources = false
          getList()
        })
      }
    }
  })
}

const arr = ['暗色', '亮色', '动漫', '科技', '美女', '风景', '春节', '喜庆', '运动', '悲伤', '快乐']
const checkList = ref<string[]>([])
const remarkChange = () => {
  if (!checkList.value.length) {
    return
  }
  form.value.remark = checkList.value.toString()
}

onMounted(() => {
  getList()
})
</script>

<template>
  <el-container class="pt-5 gap-3" direction="vertical">
    <el-container class="pb-2 px-5" direction="vertical">
      <QueryForm
        :search="getList"
        :type="ClassifyEnum.RESOURCES"
        @update="
          (args: Record<string, any>) => {
            page.param = args
          }
        "
      />
      <el-container class="gap-3 flex-wrap">
        <el-button class="!px-2 !m-0" plain type="primary" @click="handleAdd">
          <SvgIcon message="新增" name="add" />
        </el-button>
        <el-button
          :disabled="ids.length === 0"
          class="!px-2 !m-0"
          plain
          type="danger"
          @click="handleDelete(ids)"
        >
          <SvgIcon message="删除" name="delete" />
        </el-button>
      </el-container>
    </el-container>
    <el-table :data="pageVO.list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="35" />
      <el-table-column label="资源名" prop="name" />
      <el-table-column label="图片" prop="url" width="120">
        <template #default="scope">
          <el-image
            :src="scope.row.url"
            class="rounded"
            lazy
            @click="systemStore.imgPreview.imgUrl = scope.row.url"
          />
        </template>
      </el-table-column>
      <el-table-column label="标签" prop="label.name" width="80" />
      <el-table-column label="大小KB" prop="size" sortable width="120" />
      <el-table-column label="URL" prop="url" show-overflow-tooltip />
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="创建时间" prop="createTime" width="120" />
      <el-table-column label="状态" prop="status" width="70">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'danger'">
            {{ scope.row.status ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="110">
        <template #default="scope">
          <el-button class="!p-2 !m-1" type="primary" @click="handleUpdate(scope.row)">
            <SvgIcon name="edit" />
          </el-button>
          <el-button
            v-if="!scope.row.status"
            class="!p-2 !m-1"
            type="success"
            @click="handleChangeStatus(scope.row.id, true)"
          >
            <SvgIcon name="refresh" />
          </el-button>
          <el-button
            v-else
            class="!p-2 !m-1"
            type="danger"
            @click="handleChangeStatus(scope.row.id, false)"
          >
            <SvgIcon name="error" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <PageBox
      :total="pageVO.total"
      @update="
        (args: PageDTO) => {
          page.size = args.size
          page.current = args.current
          getList()
        }
      "
    />
    <!-- 添加或修改对话框 -->
    <DialogTemplate :attribute="DialogEnum.RESOURCES">
      <template #default>
        <el-container class="gap-5" direction="vertical">
          <span class="text-center">{{ isAdd ? '新增资源' : '修改资源' }}</span>
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            class="gap-1 flex flex-col"
            label-position="left"
            label-width="70px"
          >
            <el-form-item label="资源名" prop="name">
              <el-input v-model="form.name" placeholder="请输入" />
            </el-form-item>
            <ClassifyLabelForm :type="ClassifyEnum.RESOURCES" />
            <el-form-item v-if="isAdd" label="文件" prop="url">
              <UploadImg :multiple="9" />
            </el-form-item>
            <el-form-item v-else label="文件" label-position="top">
              <el-image :src="form.url" class="max-w-96 use-radius" />
            </el-form-item>
            <el-form-item label="备注" label-position="top">
              <el-checkbox-group v-model="checkList" @change="remarkChange">
                <el-checkbox v-for="p in arr" :key="p" :label="p" :value="p" />
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <el-container class="justify-between">
            <el-button type="info" @click="systemStore.dialog.resources = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </el-container>
        </el-container>
      </template>
    </DialogTemplate>
  </el-container>
</template>
